//
//  BaseViewController.m
//  SystemLocationDemo
//
//  Created by company_2 on 2017/8/28.
//  Copyright © 2017年 余东洋. All rights reserved.
//

#import "BaseViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface AddressModel()

/** 当前经度 */
@property (nonatomic,assign) CGFloat      latitude;
/** 当前纬度 */
@property (nonatomic,assign) CGFloat      longitude;
/** 国家名 -- 中国 */
@property (nonatomic,copy)   NSString   * Country;
/** 当前城市--成都 */
@property (nonatomic,copy)   NSString   * City;
/** 当前位置--武侯区 */
@property (nonatomic,copy)   NSString   * SubLocality;
/** 当前街道--天府大道中段*/
@property (nonatomic,copy)   NSString   * Street;
/** 具体地址--天府大道中段1258号 */
@property (nonatomic,copy)   NSString   * DetailStreet;




@end

@implementation AddressModel



@end


@interface BaseViewController ()<CLLocationManagerDelegate>

@property (nonatomic,strong) CLLocationManager       *locationManager;

@property (nonatomic,copy)   LocationBlock             locBlock;
/** 弹出框取消回调代码块 */
@property (nonatomic,copy)   AlertMessageCancelBlock   alertMessageCancelBlock;
/** 弹出框确定回调代码块 */
@property (nonatomic,copy)   AlertMessageSubmitBlock   alertMessageSubmitBlock;




@end

@implementation BaseViewController

-(CLLocationManager *)locationManager
{
    if ([CLLocationManager locationServicesEnabled]) {
        if (!_locationManager) {
            _locationManager = [[CLLocationManager alloc]init];
            _locationManager.delegate = self;
            [_locationManager requestAlwaysAuthorization];
            _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            _locationManager.distanceFilter = 5.0;
            [_locationManager requestWhenInUseAuthorization];

            return _locationManager;
        }
    }
    else{
//        NSLog(@"尚未打开定位设置");
        self.locBlock(nil, LocStatusForNotTurnOnSetting);
    }
    return nil;
    
}

-(void)StartLocactionWithBlock:(LocationBlock)locationBlock
{
    self.locBlock = locationBlock;
    [self.locationManager startUpdatingLocation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}


#pragma mark 定位相关协议方法：
/**
 * 定位失败的方法
 */
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    [self alertBytitle:@"是否去设置里打开定位？" message:nil submitBlock:^{
        NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication]openURL:settingURL options:@{} completionHandler:nil];
    } cancelBlock:nil];
    
    self.locBlock(nil, LocStatusForLocFaild);
}
/**
 *  定位成功的方法：
 */
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation*> *)locations{
    
    [_locationManager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    AddressModel * addressModel = [[AddressModel alloc]init];
    addressModel.longitude = currentLocation.coordinate.longitude;
    addressModel.latitude = currentLocation.coordinate.latitude;
    //这里的代码是为了判断didUpdateLocations调用了几次 有可能会出现多次调用 为了避免不必要的麻烦 在这里加个if判断 如果大于1.0就return
//    NSTimeInterval locationAge = -[currentLocation.timestamp timeIntervalSinceNow];
//    if (locationAge > 1.0){//如果调用已经一次，不再执行
//        return;
//    }
    //地理反编码 可以根据坐标(经纬度)确定位置信息(街道 门牌等)
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks.count >0) {
            CLPlacemark *placeMark = placemarks[0];
            if (!placeMark.locality) {
                NSLog(@"无法定位当前城市");
            }
            addressModel.Country = placeMark.country;
            addressModel.City = placeMark.locality;
            addressModel.SubLocality = placeMark.subLocality;
            addressModel.Street = placeMark.thoroughfare;
            addressModel.DetailStreet = placeMark.name;
            self.locBlock(addressModel, LocStatusForAllLocSuccess);
            
        }else if (error == nil && placemarks.count){
            
//            NSLog(@"NO location and error return");
            self.locBlock(addressModel, LocStatusForGeoCoderError);
            
        }else if (error){
            self.locBlock(addressModel, LocStatusForGeoCoderError);
//            NSLog(@"loction error:%@",error);
            
        }
    }];
}


#pragma mark 弹框方法：
/** 弹出框 */
-(void)alertBytitle:(NSString *)title message:(NSString *)message submitBlock:(AlertMessageSubmitBlock)submitBlock cancelBlock:(AlertMessageCancelBlock)cancelBlock
{
    self.alertMessageCancelBlock = cancelBlock;
    self.alertMessageSubmitBlock = submitBlock;
    
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        if (self.alertMessageCancelBlock) {
            self.alertMessageCancelBlock();
        }
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        if (self.alertMessageSubmitBlock){
            self.alertMessageSubmitBlock();
        }
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}



@end
